package com.tiger.admin.http.otherUser;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tiger.admin.Db;
import com.tiger.admin.SaveOperateLog;
import com.tiger.admin.dto.PaginationResult;
import com.tiger.admin.http.common.member.MemberService;
import com.tiger.admin.http.otherUser.dto.PageDto;
import com.tiger.admin.http.otherUser.type.OtherUserRes;
import com.tiger.admin.http.schoolDept.SchoolDeptService;
import com.tiger.db.entity.OtherUser;
import com.tiger.db.entity.SchoolDept;
import com.tiger.db.entity.Teacher;
import com.tiger.utils.ResponseUtil;
import com.tiger.utils.Utils;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.time.Instant;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/otherUser")
public class OtherUserController {

    private final MemberService memberService;

    private final OtherUserService otherUserService;
    private final SchoolDeptService schoolDeptService;
    private final Db db;

    public OtherUserController(MemberService memberService, OtherUserService otherUserService, SchoolDeptService schoolDeptService, Db db) {
        this.memberService = memberService;
        this.otherUserService = otherUserService;
        this.schoolDeptService = schoolDeptService;
        this.db = db;
    }

    @PostMapping("page")
    public Object page(@RequestBody PageDto page, @RequestAttribute("memberId") long memberId) {
        PaginationResult<OtherUserRes> result = new PaginationResult<>();

        LambdaQueryWrapper<OtherUser> wrapper = new LambdaQueryWrapper<>();

        if(page.getName() != null && !page.getName().isEmpty()) {
            wrapper.eq(OtherUser::getName, page.getName());
        }
        if(page.getGh() != null && !page.getGh().isEmpty()) {
            wrapper.eq(OtherUser::getGh, page.getGh());
        }


        if(page.getDeptCode() != null && !page.getDeptCode().isEmpty()) {
            List<SchoolDept> subDepts = schoolDeptService.querySubDeptsByCode(page.getDeptCode());
            if(subDepts == null) {
                return ResponseUtil.successRes(result);
            }

            List<String> deptCodes = subDepts.stream().map(SchoolDept::getCode).collect(Collectors.toList());

            deptCodes.add(page.getDeptCode());

            if(deptCodes.size() == 1) {
                wrapper.eq(OtherUser::getDeptCode, deptCodes.get(0));
            }else {
                wrapper.in(OtherUser::getDeptCode, deptCodes);
            }

        }

        long total = db.otherUser.count(wrapper);
        if(total > 0) {
            result.setTotal(total);

            wrapper.orderByDesc(OtherUser::getId);


            List<OtherUserRes> resRows = new ArrayList<>();
            List<OtherUser> rows = db.otherUser.pagination(wrapper, page.getPageNo(), page.getPageSize());

            List<String> deptCodes = new ArrayList<>();

            for(OtherUser row : rows) {
                if(row.getTel() != null && !row.getTel().isEmpty()) {
                    row.setTel(Utils.maskMobileNumber(row.getTel()));
                }

                row.setName(Utils.maskName(row.getName()));
                row.setGh(Utils.maskUserAccount(row.getGh()));

                if(!row.getDeptCode().isEmpty()) {
                    deptCodes.add(row.getDeptCode());
                }

                OtherUserRes res = new OtherUserRes();
                BeanUtils.copyProperties(row, res);
                resRows.add(res);
            }

            if(!deptCodes.isEmpty()) {
                LambdaQueryWrapper<SchoolDept> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.select(SchoolDept::getCode, SchoolDept::getName);
                List<SchoolDept> depts = db.schoolDept.list(deptCodes.size() == 1 ? queryWrapper.eq(SchoolDept::getCode, deptCodes.get(0)) : queryWrapper.in(SchoolDept::getCode, deptCodes));

                if(!depts.isEmpty()) {
                    Map<String, String> deptMap = new HashMap<>();
                    for(SchoolDept dept : depts) {
                        deptMap.put(dept.getCode(), dept.getName());
                    }

                    for(OtherUserRes row : resRows){
                        if(deptMap.containsKey(row.getDeptCode())) {
                            row.setDeptName(deptMap.get(row.getDeptCode()));
                        }
                    }
                }
            }

            result.setRows(resRows);
        }


        return ResponseUtil.successRes(result);
    }

    @SaveOperateLog("新增其他人员")
    @PostMapping("add")
    public Object add(@RequestBody @Validated OtherUser data, @RequestAttribute("memberId") long memberId) {
        if(db.otherUser.exists(new LambdaQueryWrapper<OtherUser>().eq(OtherUser::getGh, data.getGh()))) {
            return ResponseUtil.failRes("已存在相同的工号");
        }


        data.setSource(2);

        Instant now = Instant.now();

        data.setCreateTime(now.getEpochSecond());
        data.setSource(2);
        boolean r = db.otherUser.save(data);

        return r ? ResponseUtil.successRes(data) : ResponseUtil.failRes();

    }


    @SaveOperateLog("修改其他人员")
    @PostMapping("update/{id}")
    public Object add(@RequestBody @Validated OtherUser data, @PathVariable Long id, @RequestAttribute("memberId") long memberId) {
        OtherUser row = db.otherUser.getById(id);
        if(row == null) return ResponseUtil.successRes();
        if(data.getGh() != null && !data.getGh().equals(row.getGh())) {
            if(db.otherUser.exists(new LambdaQueryWrapper<OtherUser>().eq(OtherUser::getGh, data.getGh()))) {
                return ResponseUtil.failRes("已存在相同的工号");
            }
        }


        Instant now = Instant.now();

        Utils.copyPropertiesIgnoreNull(data, row);

        row.setUpdateTime(now.getEpochSecond());



        boolean r = db.otherUser.updateById(row);

        return r ? ResponseUtil.successRes(row) : ResponseUtil.failRes();

    }


    @SaveOperateLog("删除其他人员")
    @PostMapping("delete/{id}")
    public Object del(@PathVariable long id, @RequestAttribute("memberId") long memberId) {
        OtherUser row = db.otherUser.getOne(new LambdaQueryWrapper<OtherUser>().select(OtherUser::getId).eq(OtherUser::getId, id));
        if(row == null) return ResponseUtil.successRes();
        boolean r = db.otherUser.removeById(id);
        return r ? ResponseUtil.successRes() : ResponseUtil.failRes();
    }


    /**
     * 导入用户
     * **/
    @SaveOperateLog("导入其他人员")
    @PostMapping("import")
    public Object importApps(@RequestParam("file") MultipartFile file, @RequestAttribute("memberId") long memberId) {

        otherUserService.importUser(file);

        return ResponseUtil.successRes();
    }

    /**
     * 查看敏感信息
     * */
    @PostMapping("secrecy/{userId}")
    public Object secrecy(@RequestBody() HashMap<String, String> data, @PathVariable("userId") int userId, HttpSession session) {
        String password = data.get("password");
        String field = data.get("field");
        if(password == null || password.isEmpty()) return ResponseUtil.failRes();
        if(field == null || field.isEmpty()) return ResponseUtil.failRes();

        if(session.getAttribute(password) == null) return ResponseUtil.failRes("密码错误");

        LambdaQueryWrapper<OtherUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OtherUser::getId, userId);

        if(field.equals("name")) {
            wrapper.select(OtherUser::getName);
        }else if(field.equals("gh")) {
            wrapper.select(OtherUser::getGh);
        }else if(field.equals("tel")) {
            wrapper.select(OtherUser::getTel);
        }else {
            return ResponseUtil.failRes();
        }

        OtherUser otherUser = db.otherUser.getOne(wrapper);


        return ResponseUtil.successRes(otherUser);
    }
}
